package com.ezjie.login;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.wechat.friends.Wechat;

import com.alibaba.fastjson.JSON;
import com.ezjie.baselib.core.base.BaseFragmentActivity;
import com.ezjie.baselib.spfs.SharedPrefHelper;
import com.ezjie.baselib.util.AppUtil;
import com.ezjie.baselib.util.LogUtils;
import com.ezjie.baselib.util.NetworkUtil;
import com.ezjie.baselib.util.OnDialogBtnClickImpl;
import com.ezjie.login.constant.Constants;
import com.ezjie.login.core.http.HttpRequestAbstractCallBack;
import com.ezjie.login.db.UserInfoDB;
import com.ezjie.login.model.UserData;
import com.ezjie.login.model.UserDetail;
import com.ezjie.login.model.UserInfo;
import com.ezjie.login.task.LoginTask;
import com.ezjie.login.task.WeixinLoginTask;
import com.ezjie.login.util.StringUtil;
import com.ezjie.login.util.UmengPages;
import com.ezjie.login.widget.AppWarnDialog;
import com.ezjie.login.widget.LinearLayoutView;
import com.ezjie.login.widget.LinearLayoutView.KeyBordStateListener;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

public class LoginActivity extends BaseFragmentActivity implements Callback, PlatformActionListener {
	
	
	
	private LinearLayoutView resizeLayout;
	private ImageView iv_login_back;
	private Context mContext;
	private static final int MSG_USERID_FOUND = 1;
	private static final int MSG_LOGIN = 2;
	private static final int MSG_AUTH_CANCEL = 3;
	private static final int MSG_AUTH_ERROR = 4;
	private static final int MSG_AUTH_COMPLETE = 5;
	private LoginTask loginTask;
	private WeixinLoginTask weixinLoginTask;
	private UserInfoDB mUserInfoDB;
private EditText et_username;
private EditText et_password;
private Button btn_login;
private Button btn_forget_password;
private TextView tv_login_by_weichat;
	private TextView tv_register_btn;
	private ImageView loginLogo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_app_login);
		iv_login_back=(ImageView)this.findViewById(R.id.login_back_btn);
		et_username = (EditText)this.findViewById(R.id.email);
		et_password = (EditText)this.findViewById(R.id.password);
		btn_login = (Button)this.findViewById(R.id.submit_btn);
		btn_forget_password = (Button)this.findViewById(R.id.btn_forget_password);
		tv_login_by_weichat = (TextView)this.findViewById(R.id.login_by_weichat);
		tv_register_btn = (TextView)this.findViewById(R.id.register_btn);
		loginLogo =(ImageView)this.findViewById(R.id.login_logo);
		resizeLayout = (LinearLayoutView) this.findViewById(R.id.ll_login_view);
		ViewUtils.inject(this);
		ShareSDK.initSDK(this);
		loginTask = new LoginTask(this);
		weixinLoginTask = new WeixinLoginTask(this);
		mUserInfoDB = new UserInfoDB(this);

		mContext = this;
		init();
	}

	@Override
	public void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_LOGIN);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_LOGIN);
	}

	private void init() {
		iv_login_back.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		tv_login_by_weichat.setOnClickListener(this);
		tv_register_btn.setOnClickListener(this);
		btn_forget_password.setOnClickListener(this);

		// textview下划线设置
		tv_login_by_weichat.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		tv_register_btn.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

		resizeLayout.setKeyBordStateListener(new KeyBordStateListener() {

			@Override
			public void stateChange(int state) {
				switch (state) {
				case LinearLayoutView.KEYBORAD_HIDE:
					loginLogo.setVisibility(View.VISIBLE);
					break;
				case LinearLayoutView.KEYBORAD_SHOW:
					loginLogo.setVisibility(View.GONE);
					break;
				}
			}
		});

		et_username.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				loginEnable();
			}
		});
		et_password.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				loginEnable();
			}
		});
	}

	/**
	 * 判断登录按钮是否可以点击
	 * 
	 * @param username
	 * @param password
	 */
	private void loginEnable() {
		String username = et_username.getText().toString();
		String password = et_password.getText().toString();
		if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || password.length() < 6) {
			btn_login.setEnabled(false);
			btn_login.setTextColor(Color.argb(127, 255, 255, 255));
		} else {
			btn_login.setEnabled(true);
			btn_login.setTextColor(Color.WHITE);
		}
	}

	@Override
	public void onClickEvent(View view) {
		if(view.getId() == R.id.login_back_btn){
			finish();
		}else if(view.getId()==R.id.submit_btn){
			login();
		}else if(view.getId()==R.id.login_by_weichat){
			if(AppUtil.isFastClick()){
				return;
			}
			authorize(new Wechat(this));
		}else if(view.getId()==R.id.register_btn){
			Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivityForResult(intent, Constants.REQUEST_REG);
		}else if(view.getId()==R.id.btn_forget_password){
			// 忘记密码
			Intent forgetIntent = new Intent(LoginActivity.this, ForgetPassActivity.class);
			forgetIntent.putExtra("username", et_username.getText().toString());
			startActivityForResult(forgetIntent, Constants.REQUEST_FORGET_PASS);
		}

	}
//
	private void login() {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}
		String username = et_username.getText().toString();
		if (TextUtils.isEmpty(username)) {
			AppUtil.showToast(mContext, R.string.login_input_correct_email);
			return;
		}

		String password = et_password.getText().toString();
		if (!StringUtil.checkPassword(password)) {
			AppUtil.showToast(mContext, R.string.login_input_correct_password);
			return;
		}

		int sendType;
		if (AppUtil.mobileFormat(username)) {
			sendType = 1;
		} else if (AppUtil.emailFormat(username)) {
			sendType = 2;
		} else {
			sendType = 2;
		}

		loginTask.doLogin(sendType, username, password, new HttpRequestAbstractCallBack(this,false) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				AppUtil.dismissProgressDialog();
				try {
					UserInfo info = JSON.parseObject(result, UserInfo.class);
					if (info != null && info.getStatus_code() == 200) {
						AppUtil.showToast(LoginActivity.this, R.string.login_success);
						UserData data = info.getData();
						System.out.println(data!=null);
						if (data != null) {
							
							String login_token = data.getLogin_token();
							UserDetail user = data.getUser();
							SharedPrefHelper.getInstance().setLoginKey(user.login_key);
							SharedPrefHelper.getInstance().setLoginUid(user.uid);

							user.login_key = login_token;
							user.islogin = 1;
							// 判断uid是否存在
							boolean existUid = mUserInfoDB.isExistUid(user.uid);
							if (existUid) {
								mUserInfoDB.update(user);
							} else {
								mUserInfoDB.insert(user);
							}
							finish();
						}

					} else {
						String msg = info.getMsg();
						if (TextUtils.isEmpty(msg)) {
							msg = LoginActivity.this.getResources().getString(R.string.login_fail);
						}
						final AppWarnDialog appWarnDialog = new AppWarnDialog(LoginActivity.this, R.style.customDialog);
						appWarnDialog.show();
						appWarnDialog.setOneButton(true);
						appWarnDialog.setMessage(msg);
						appWarnDialog.setKnowButton(R.string.confirm);
						appWarnDialog.setListener(new OnDialogBtnClickImpl() {
							@Override
							public void onKnowClick() {
								appWarnDialog.cancel();
							}
						});
					}

				} catch (Exception e) {
					LogUtils.exception(e);
				}

			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				System.out.println("失败");
				Toast.makeText(LoginActivity.this, "失败", 0).show();
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(LoginActivity.this, R.string.load_net_data_failure);
			}
		});
	}

	/******************** 微信登录 *************************************/
	private void login(String plat, String userId, HashMap<String, Object> userInfo, Platform platform) {
		Message msg = new Message();
		msg.what = MSG_LOGIN;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}

	private void authorize(Platform plat) {
		AppUtil.showProgressDialog(LoginActivity.this);
		if (plat.isValid()) {
			String userId = plat.getDb().getUserId();
			if (!TextUtils.isEmpty(userId)) {
				UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
				login(plat.getName(), userId, null, plat);
				return;
			}
		}
		plat.setPlatformActionListener(this);
		plat.SSOSetting(true);
		plat.showUser(null);
	}

	private void weixinLoginUser(String assetsToken, String openid) {
		weixinLoginTask.doLogin(assetsToken, openid, new HttpRequestAbstractCallBack(this,false) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();

			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				System.out.println("微信登录：" + result);
				try {
					UserInfo info = JSON.parseObject(result, UserInfo.class);
					if (info != null && info.getStatus_code() == 200) {
						AppUtil.showToast(LoginActivity.this, R.string.login_success);
						UserData data = info.getData();
						if (data != null) {
							String login_token = data.getLogin_token();
							UserDetail user = data.getUser();
							user.login_key = login_token;
							user.islogin = 1;
							// 判断uid是否存在
							boolean existUid = mUserInfoDB.isExistUid(user.uid);
							if (existUid) {
								mUserInfoDB.update(user);
							} else {
								mUserInfoDB.insert(user);
							}

							finish();
						}

					} else {
						String msg = info.getMsg();
						if (TextUtils.isEmpty(msg)) {
							msg = LoginActivity.this.getResources().getString(R.string.login_fail);
						}
						final AppWarnDialog appWarnDialog = new AppWarnDialog(LoginActivity.this, R.style.customDialog);
						appWarnDialog.show();
						appWarnDialog.setOneButton(true);
						appWarnDialog.setMessage(msg);
						appWarnDialog.setKnowButton(R.string.confirm);
						appWarnDialog.setListener(new OnDialogBtnClickImpl() {
							@Override
							public void onKnowClick() {
								appWarnDialog.cancel();
							}
						});
					}

				} catch (Exception e) {
					LogUtils.exception(e);
				}

			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(LoginActivity.this, R.string.load_net_data_failure);
			}
		});
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_USERID_FOUND: {
			AppUtil.showToast(mContext, R.string.userid_found);
		}
			break;
		case MSG_LOGIN: {
			Platform platform = (Platform) msg.obj;
			weixinLoginUser(platform.getDb().getToken(), platform.getDb().getUserId());
		}
			break;
		case MSG_AUTH_CANCEL: {
			AppUtil.showToast(mContext, R.string.auth_cancel);
			AppUtil.dismissProgressDialog();
		}
			break;
		case MSG_AUTH_ERROR: {
			AppUtil.showToast(mContext, R.string.auth_error);
			AppUtil.dismissProgressDialog();
		}
			break;
		case MSG_AUTH_COMPLETE: {

		}
			break;
		}
		return false;
	}

	@Override
	public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
		if (action == Platform.ACTION_USER_INFOR) {
			UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
			login(platform.getName(), platform.getDb().getUserId(), res, platform);
		}
	}

	@Override
	public void onError(Platform platform, int action, Throwable t) {
		if (action == Platform.ACTION_USER_INFOR) {
			UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
		}
		t.printStackTrace();
	}

	@Override
	public void onCancel(Platform platform, int action) {
		if (action == Platform.ACTION_USER_INFOR) {
			UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_REG) {
			// 注册成功返回的
			this.setResult(RESULT_OK);
			this.finish();
		}
		if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_FORGET_PASS) {
			// 修改密码成功返回的

		}
	}


}